package com.ustc.phoenix.mybatis;

import com.ustc.phoenix.models.Blog;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * Created by firephoenix on 5/24/16.
 * Two way to select Object from mysql
 */
@Component
public class Mybatis {
    Blog blog;
    @Autowired
    SqlSessionFactory sqlSessionFactory;
    /**
     * Select using xml configuration
     * @param i
     * @return
     * @throws Exception
     */
   public Blog selectBlog(int i) throws Exception{
       //Resources.getResourceAsStream(path) without '/' it will get resource in this package.
       /*String resource = "com/ustc/phoenix/mybatisConf/mybatis-config.xml";
       InputStream inputStream=Resources.getResourceAsStream(resource);
       SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
       */
       SqlSession session = sqlSessionFactory.openSession();

       try {
           blog = session.selectOne("com.ustc.phoenix.mapper.BlogMapper.selectBlog", 1);
       } finally {
           session.close();
       }       return blog;
   }

    /**
     * Select using *.java
     * @return
     * @throws Exception
     */
   public Blog selectBlog() throws Exception{
        /*String resource = "com/ustc/phoenix/mybatisConf/mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        */
       SqlSession session = sqlSessionFactory.openSession();
        try {
          //  BlogMapper mapper = session.getMapper(BlogMapper.class);
           // blog = mapper.selectBlog(1);
        } finally {
            session.close();
        }
        return blog;
    }
}